<?php

namespace app\shopapi\controller;



use app\common\controller\Shopapi;
use app\shopapi\model\ShopAdmin;
use app\common\library\Sms;

/**
 * 员工接口
 */
class Admin extends Shopapi
{
    protected $noNeedRight = '*';


    public function create()
    {
        $realname = input('realname','');
        $mobile = input('mobile','');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }

        if (!Sms::check($mobile, $captcha, 'createadmin')) {
            $this->error('验证码错误');
        }
        $shop = \app\shopapi\model\Shop::get($this->shopauth->shop_id);
        $admin_model = new ShopAdmin();
        $data = [
            'shop_id'=>$this->shopauth->shop_id,
            'group_id'=>input('group_id',0),
            'realname'=>$realname,
            'mobile'=>$mobile,
            'shop_no'=>$shop->shop_no,
            'collection_code'=>$shop->shop_no.'-'.\fast\Random::numeric(6)
        ];
        if (empty($data['realname']))$this->error('请输入姓名');
        if (empty($data['mobile']))$this->error('请输入手机号');
        $res = $admin_model->save($data);
        if ($res){
            $this->success('添加成功');
        } else {
            $this->error('添加失败');
        }
    }

    public function edit()
    {
        $id = input('id',0);
        $realname = input('realname',0);
        $mobile = input('mobile','');
        $group_id = input('group_id',0);
        if (empty($realname))$this->error('请输入姓名');
        if (empty($mobile))$this->error('请输入手机号');
        $detail = ShopAdmin::get($id);
        $detail->realname = $realname;
        $detail->mobile = $mobile;
        $detail->group_id = $group_id;
        $res = $detail->save();
        $this->success('编辑成功');
    }

    public function del()
    {
        $id = input('id',0);
        $detail = ShopAdmin::get($id);
        if ($detail->delete()){
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    public function lists()
    {
        $list = ShopAdmin::alias('sa')
            ->join('shop_auth_group sag','sa.group_id = sag.id')
            ->where(['sa.shop_id'=>$this->shopauth->shop_id,'sa.is_applicant'=>0])
            ->field('sa.*,sag.name')->select();
            //->paginate(10, false, ['query' => request()->get()]);
        $this->success('',$list);
    }

    public function admin()
    {
        $list = ShopAdmin::alias('sa')
            //->join('shop_auth_group sag','sa.group_id = sag.id')
            ->where(['sa.shop_id'=>$this->shopauth->shop_id])
            ->field('sa.*')->select();
        foreach ($list as $k=>$v){
            if ($v['is_applicant']==1){
                $list[$k]['realname'] = '老板';
            }
        }
        //->paginate(10, false, ['query' => request()->get()]);
        $this->success('',$list);
    }
}